<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { selectAllApi, selectByNameApi, deleteGroupApi, deleteApi, insertApi, updateApi } from '@/api/courseCategory.js'

// 查询条件
const searchName = ref('');

// 表格数据
const tableData = ref([]);
const multipleSelection = ref([]);
const loading = ref(false);

// 分页参数
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 对话框状态
const dialogVisible = ref(false);
const dialogTitle = ref('新增课程分类');
const formData = ref({
  id: null,
  categoryName: '',
  parentCategoryId: null,
});
const formRules = {
  name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
};

// 父分类映射
const parentCategoryMap = {
  1: '咨询师培训',
  2: '智慧生活',
  3: '教师板块',
  4: '身心医生',
  5: '免费公开课',
};

// 数据获取
onMounted(() => {
  fetchData();
});

// 获取表格数据
const fetchData = async () => {
  loading.value = true;
  try {
    //获取分页数据
    const res = await selectAllApi({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
    });
    if (res.code === 200) {
      tableData.value = res.data.list.filter(item => item.isDeleted === 0);
      total.value = res.data.total;
    } else {
      console.error("查询失败：", res.data.msg);
    }
  } catch (error) {
    console.error("请求失败：", error.message);
    alert("网络错误，请稍后重试");
  } finally {
    loading.value = false;
  }
};

// 模糊查询
const handleSearch = async () => {
  try {
    //获取分页数据
    const res = await selectByNameApi({
      name: searchName.value,
      pageNum: currentPage.value,
      pageSize: pageSize.value,
    });
    if (res.code === 200) {
      tableData.value = res.data.list.filter(item => item.isDeleted === 0);
      total.value = res.data.total;
      ElMessage.success('搜索成功');
    } else {
      console.error("查询失败：", res.data.msg);
    }
  } catch (error) {
    console.error("请求失败：", error.message);
    alert("网络错误，请稍后重试");
  }
};

// 多选变化
const handleSelectionChange = (val) => {
  multipleSelection.value = val.map((item) => item.id);
};

// 批量删除
const handleBatchDelete =  async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请至少选择一条数据');
    return;
  }
  try {
    await ElMessageBox.confirm("确定要删除选中的分类吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    loading.value = true;
    const categoryIds = multipleSelection.value;// 假设是 [1, 2, 3]
    const res = await deleteGroupApi(categoryIds);
    if (res.code === 200) {
      ElMessage.success("批量删除成功");
      await fetchData(); // 刷新数据
    } else {
      ElMessage.error(res.data.msg || "批量删除失败");
    }
  } catch(error) {
    if (error === "cancel") {
      ElMessage.info("已取消删除");
    } else {
      console.error("批量删除错误:", error);
      ElMessage.error("删除失败，请稍后重试");
    }
  } finally {
    loading.value = false;
  }
};

//单个删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除分类 ${row.categoryName} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    //调用删除接口
    await deleteApi(row.id);
    ElMessage.success(`删除分类 ${row.categoryName} 成功`);
    await fetchData();
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 打开新增对话框
const handleAdd = () => {
  dialogTitle.value = '新增课程分类';
  formData.value = { id: null, categoryName: '', parentCategoryId: null };
  dialogVisible.value = true;
};

// 打开编辑对话框
const handleEdit = (row) => {
  dialogTitle.value = '编辑课程分类';
  formData.value = { id: row.id, categoryName: row.categoryName, parentCategoryId: row.parentCategoryId };
  dialogVisible.value = true;
};

// 提交表单（新增或编辑）
const handleSubmit = async () => {
  // 调用新增或编辑接口
  if (formData.value.id) {
    // 编辑
    await updateApi(formData.value);
    ElMessage.success(`编辑分类 ${formData.value.categoryName} 成功`);
  } else {
    // 新增
    await insertApi(formData.value);
    ElMessage.success(`新增分类 ${formData.value.categoryName} 成功`);
  }
  dialogVisible.value = false;
  fetchData();
};

// 分页变化
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchData();
};

const handlePageSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1; // 重置到第一页
  fetchData();
};
</script>

<template>
  <div class="page-content">
    <!-- 查询区域 -->
    <div class="search-bar">
      <el-input
        v-model="searchName"
        placeholder="请输入分类名称"
        clearable
        style="width: 200px; margin-right: 10px;"
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button type="success" @click="handleAdd" style="margin-left: 10px;">新增分类</el-button>
      <el-button type="danger" @click="handleBatchDelete">删除分类</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
      :data="tableData"
      style="width: 100%; margin-top: 20px;"
      @selection-change="handleSelectionChange"
      border
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="100" />
      <el-table-column prop="categoryName" label="分类名称" width="200" />
      <el-table-column label="父分类名称" width="200">
        <template #default="{ row }">
          {{ parentCategoryMap[row.parentCategoryId] || '无' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button type="default" @click="handleEdit(row)" class="text-button">编辑课程分类</el-button>
          <el-button type="default" style="color: #f56c6c;" @click="handleDelete(row)" class="text-button">删除课程分类</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 30, 50]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      style="margin-top: 20px; justify-content: flex-end;"
      @size-change="handlePageSizeChange"
      @current-change="handlePageChange"
    />

    <!-- 对话框（新增/编辑复用） -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="30%"
      :before-close="() => dialogVisible = false"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef">
        <el-form-item label="分类名称" prop="name" label-width="100px">
          <el-input v-model="formData.categoryName" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="父分类" label-width="100px">
          <el-select v-model="formData.parentCategoryId" placeholder="请选择父分类" style="width: 100%;" clearable>
            <el-option
              v-for="(name, id) in parentCategoryMap"
              :key="id"
              :label="name"
              :value="parseInt(id)"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.text-button {
  color: #606266; /* 模仿 text 样式的颜色 */
  background: none;
  border: none;
  padding: 0;
}
.page-content {
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.el-button {
  border-radius: 8px;
}

.el-button--primary {
  background: linear-gradient(90deg, #409eff, #79bbff);
  border: none;
}

.el-button--primary:hover {
  background: linear-gradient(90deg, #337ecc, #66aaff);
}

.el-button--success {
  background: linear-gradient(90deg, #67c23a, #95d475);
  border: none;
}

.el-button--success:hover {
  background: linear-gradient(90deg, #5daf34, #85c265);
}

.el-button--danger {
  background: linear-gradient(90deg, #f56c6c, #ff9999);
  border: none;
}

.el-button--danger:hover {
  background: linear-gradient(90deg, #e65a5a, #ff8888);
}
</style>
